package com.longtop.framework.sys.team.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.longtop.framework.base.BaseService;
import com.longtop.framework.common.Constant;
import com.longtop.framework.common.QueryConditions;
import com.longtop.framework.common.QueryResult;
import com.longtop.framework.security.BaseCheckedException;
import com.longtop.framework.security.SessionObject;
import com.longtop.framework.util.BeanUtil;
import com.longtop.framework.util.ReflectUtil;
import com.longtop.framework.util.WebUtil;
import com.longtop.intelliweb.view.Dataset;

/**
 * 系统管理-群组SERVICE
 * 
 * @author SJH
 */
public class TeamService extends BaseService {

	public static final String BEAN_ID = "groupTeamService";

	/**
	 * 提交保存群组(员工/机构)
	 * 
	 * @param changeMap
	 * @param entityClass
	 *            员工或则机构的群组类CLASS
	 * @return
	 */
	public Integer[] saveTeam(Map changeMap, Class entityClass, SessionObject sessionObject) {

		// 插入成功的记录数、更新成功的记录数、删除成功的记录数
		int insertCount = 0;
		int updateCount = 0;
		int deleteCount = 0;
		// 删除主键列表、更新bean的列表、新增bean的列表
		List insertBeanList = (ArrayList) changeMap.get(Constant.INSERT_BEAN_LIST);
		List updateBeanList = (ArrayList) changeMap.get(Constant.UPDATE_BEAN_LIST);
		String idList = (String) changeMap.get(Constant.ID_LIST);

		String teamClassName = entityClass.getSimpleName();// 群组类名称
		String teamMxClassName = teamClassName + "Mx";// 群组明细类名称
		String teamId = teamMxClassName.indexOf("User") != -1 ? "userTeamId" : "orgTeamId";

		Object teamObject;// C
		Iterator iterator;

		// 批量插入记录
		if (insertBeanList.size() > 0) {
			iterator = insertBeanList.iterator();
			while (iterator.hasNext()) {
				teamObject = iterator.next();
				this.setAuthPropetryToEntity(teamObject, sessionObject, true);

				super.save(teamObject);
				insertCount++;
			}
		}

		// 批量更新记录
		if (updateBeanList.size() > 0) {
			iterator = updateBeanList.iterator();
			while (iterator.hasNext()) {
				teamObject = iterator.next();
				this.setAuthPropetryToEntity(teamObject, sessionObject, false);

				super.update(teamObject);
				updateCount++;
			}
		}

		// 批量删除记录//C
		if (idList.length() > 0) {
			// 删除主表
			String sql = "delete from " + teamClassName + " where " + teamId + " in(" + idList + ")";
			deleteCount = super.batchUpdate(sql);
			// 删除子表：
			String sqlMx = "delete from " + teamMxClassName + " where " + teamId + " in(" + idList + ")";
			super.batchUpdate(sqlMx);
		}

		return new Integer[] { new Integer(insertCount), new Integer(updateCount), new Integer(deleteCount) };
	}

	/**
	 * 提交保存群组明细(员工/机构)
	 * 
	 * @param changeMap
	 * @param entityClass
	 *            员工或则机构的群组明细类CLASS
	 * @return
	 * @throws BaseCheckedException
	 */
	public Integer[] saveTeamMx(Map changeMap, Class entityClass) throws BaseCheckedException {

		// 插入成功的记录数、更新成功的记录数、删除成功的记录数
		int insertCount = 0;
		int updateCount = 0;
		int deleteCount = 0;
		// 删除主键列表、更新bean的列表、新增bean的列表
		List insertBeanList = (ArrayList) changeMap.get(Constant.INSERT_BEAN_LIST);
		List updateBeanList = (ArrayList) changeMap.get(Constant.UPDATE_BEAN_LIST);
		String idList = (String) changeMap.get(Constant.ID_LIST);

		String teamMxClassName = entityClass.getSimpleName();// 群组明细类名称
		String objectId = teamMxClassName.indexOf("User") != -1 ? "userId" : "orgId";
		String teamId = teamMxClassName.indexOf("User") != -1 ? "userTeamId" : "orgTeamId";
		String msgObject = teamMxClassName.indexOf("User") != -1 ? "员工号：" : "机构号：";

		Object teamMxObject;// C
		Iterator iterator;

		// 批量插入记录
		if (insertBeanList.size() > 0) {
			iterator = insertBeanList.iterator();
			while (iterator.hasNext()) {
				teamMxObject = iterator.next();

				// 校验群组是否已经存在此对象：
				String teamIdValue = "" + ReflectUtil.getFieldValue(teamMxObject, teamId);
				String objectIdValue = "" + ReflectUtil.getFieldValue(teamMxObject, objectId);
				List list = this.queryAll("from  " + teamMxClassName + " where " + teamId + "='" + teamIdValue + "' and " + objectId + "='" + objectIdValue + "'");
				if (list.size() > 0) {
					continue;// 跳过已经存在的对象
				}

				super.save(teamMxObject);
				insertCount++;
			}
		}

		// 批量更新记录
		if (updateBeanList.size() > 0) {
			iterator = updateBeanList.iterator();
			while (iterator.hasNext()) {
				teamMxObject = iterator.next();

				// 校验群组是否已经存在此对象：
				String teamIdValue = "" + ReflectUtil.getFieldValue(teamMxObject, teamId);
				String objectIdValue = "" + ReflectUtil.getFieldValue(teamMxObject, objectId);
				List list = this.queryAll("from  " + teamMxClassName + " where " + teamId + "='" + teamIdValue + "' and " + objectId + "='" + objectIdValue + "'");

				if (list.size() > 0) {
					super.deleteAll(list);// 删除原存在的记录。
					// throw new BaseCheckedException("更新失败，群组已经拥有该对象【" + msgObject + objectIdValue + "】。");
				}

				super.update(teamMxObject);
				updateCount++;
			}
		}

		// 批量删除记录//C
		if (idList.length() > 0) {
			// 删除子表：
			String sqlMx = "delete from " + teamMxClassName + " where id in(" + idList + ")";
			super.batchUpdate(sqlMx);
		}

		return new Integer[] { new Integer(insertCount), new Integer(updateCount), new Integer(deleteCount) };
	}

	/**
	 * 依据条件，读取群组列表（权限控制）
	 * 
	 * @param queryConditions
	 * @return
	 */
	public Dataset getTeamByAuth(SessionObject sessionObject, Dataset teamDataset, Class teamClass) {
		// 权限控制：只允许显示本机构创建的群组（admin除外）
		QueryConditions conditions = WebUtil.createQueryConditions();
		if (!sessionObject.getUserId().equals(Constant.ADMIN)) {
			conditions.setConditionEqual("createOrgId", sessionObject.getOrgId());
		}
		QueryResult queryResult = this.loadByConditions(conditions, teamDataset.getPageNo(), teamDataset.getPageSize(), teamClass);
		BeanUtil.queryResultToDataset(queryResult, teamDataset, false, true);

		return teamDataset;
	}
}